<?php

namespace App\Http\Controllers;

use App\User;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cookie;

/**
 * Class IndexController
 *
 * @package \App\Http\Controllers
 */
class IndexController extends Controller
{
    public function index(Request $request)
    {

        if (\Session::get('userId')){
            $user = \Auth::loginUsingId(\Session::get('userId'));
            return response([
                'code' => 200,
                'user' => \Auth::user()
            ]);
        }else{
            $token = $request->input('token');
            if (!$token){
                $url = $request->fullUrl();
                return redirect('http://sso.zihai.cc/login?uri='.$url);
            }
                $client = new Client();
                $response = $client->post('http://sso.zihai.cc/checkLogin',[
                    'json' => [
                        'token' => $token
                    ]
                ]);
                $body = json_decode($response->getBody()->getContents(),true);
                if ($body['code'] == 200){
                    $user = User::query()->where('open_id',$body['user']['id'])->first();
                    if (!$user){
                        User::query()->create([
                            'name' => $body['user']['name'],
                            'open_id' => $body['user']['id']
                        ]);
                    }
                    \Auth::loginUsingId($user->id);
                    \Session::put('userId',$user->id);

                    return response([
                        'code' => 200,
                        'user' => \Auth::user()
                    ])->cookie('token',$token,3600);
                }else{
                    echo '非法登陆';
                    die();
                }
        }
    }

    public function logout()
    {

        \Session::flush();
        // 通知中心退出
        $client = new Client();
        $response = $client->post('http://sso.zihai.cc/logout',[
            'json' => [
                'token' => Cookie::get('token')
            ]
        ]);
        return response('退出成功');
    }
}
